#include "common.h"
#include <sys/ipc.h>
#include <sys/shm.h>
#include <semaphore.h>
#include <pthread.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <fcntl.h>

#define SIZE 10

//int global_num;

typedef struct _product
{
	int flag;
	int num;
}product_t;

int main()
{
	int shmid;
	key_t key;
	product_t *shmaddr = NULL;
	//int global_num = 0;

	key = ftok("./", 19);
	if(key < 0)
		err_sys("ftok error\n");

	shmid = shmget(key, SIZE, IPC_CREAT | 0666);
	if(shmid < 0)
		err_sys("shmget error\n");

	shmaddr = shmat(shmid, NULL, 0);
	printf("shmaddr : %p\n", shmaddr);
	if(shmaddr < 0)
		err_sys("shmat error\n");

	printf("global_num = %d\n", shmaddr->num);

	sem_t *sem = sem_open("tmp_sem", 0);
	if(shmaddr->flag == 1 || shmaddr->flag == 2)
	{
		sem_wait(sem);
		printf("There are %d products.\n", shmaddr->num);
		printf("How many products want to get?\n");
		int temp = 0;
		scanf("%d", &temp);
		while((shmaddr->num - temp) < 0)
		{
			printf("Sorry, there are %d products\n", shmaddr->num);
			scanf("%d", &temp);
			shmaddr->num -= temp;
			if(shmaddr->num == 0)
			{
				printf("Product is zero\n");
				shmaddr->flag = -1;
			}
			else
			{
				shmaddr->flag = 0;
				printf("There are %d products left.\n", shmaddr->num);
			}
		}
	

		sem_post(sem);
		sem_close(sem);
	}
	else if(shmaddr->flag == 0)
	{
		printf("Producer is working.\n");
	}


	int ret = shmdt(shmaddr);
	if(ret < 0)
		err_sys("shmdt error\n");

	shmctl(shmid, IPC_RMID, NULL);

	return 0;
}

